#include "Utility.h"
#include "Common/TSContainer.h"
#include "RPCHandler.h"
struct NetMessage
{
    SOCKET sender;
    SOCKET receiver;
    std::string data;
};



class NetMessenger : public BlockedServer
{
protected:
    TS::ThreadSafeQueue<NetMessage> m_reqMessage;                       //request message
    TS::ThreadSafeQueue<NetMessage> m_rspMessage;                       //response message
    BlockedClient m_Client;
    RPCHandler m_rpcHandler;
    std::thread m_thConnService;                                        //thread for Messenger - Service communication        
public:
    //pop request message to service process
    void TickToService();
    //handle respons message from service
    void HandleServiceMsg(SOCKET s, const std::string& data);
protected:
    //pop response message to client process
    void TickToClient();
public:
    std::string serviceIP = "127.0.0.1";
    int servicePort = 2018;
    void HandleClientMsg(SOCKET s, const std::string& data);
    
    NetMessenger()
    {
        this->RegisterFunction(std::bind(&NetMessenger::HandleClientMsg, this, std::placeholders::_1, std::placeholders::_2));
        m_rpcHandler.Subscribe(this);
        m_thConnService = std::thread([=]{
            while (true)
            {
                this->TickToService();
            }
        });
    }

    ~NetMessenger()
    {
        if (m_thConnService.joinable())
        {
            m_thConnService.join();
        }
    }

    virtual void Tick() override
    {
        BlockedServer::Tick();
        this->TickToClient();
    }
    void handle_msg_from_service(const json& rsp)
    {
        NetMessage msg;
        msg.receiver = rsp["receiver"];
        msg.data = rsp["data"];
        m_rspMessage.Push(msg);
    }
};

Reflect_Class(NetMessenger);
Reflect_Class_Method(NetMessenger, handle_msg_from_service);
